import { isPlainObject } from "./isPlainObject";
import { isHas } from "./isHas";
import { isString } from "./isString";
import { isNotEmpty } from "./isNotEmpty";
import { isNumber } from "./isNumber";
import { isBoolean } from "./isBoolean";

const defaultSplitIdentifier = { identifier: "?", joinSplit: "&" };

/**
 * @description 进行url 填充
 * @author lihh
 * @param url 待填充的 url
 * @param assemblyData 要填充的数据
 * @param splitIdentifier identifier 用来判断符号是否存在 一般用来是url中?号, joinSplit 这是拼接符号
 */
export function assemblyURL(
  url: string,
  assemblyData: Record<string, string | number | boolean>,
  splitIdentifier = defaultSplitIdentifier
) {
  splitIdentifier = Object.assign(
    {},
    defaultSplitIdentifier,
    !isPlainObject(splitIdentifier) ? {} : splitIdentifier
  );
  if (
    !(
      isString(url) &&
      isNotEmpty(url) &&
      isPlainObject(assemblyData) &&
      isPlainObject(splitIdentifier) &&
      isHas(splitIdentifier, "identifier") &&
      isHas(splitIdentifier, "joinSplit")
    )
  ) {
    return url;
  }

  const assemblyDataKeys = Object.keys(assemblyData).map((key) =>
    isString(assemblyData[key]) ||
    isNumber(assemblyData[key]) ||
    isBoolean(assemblyData[key])
      ? `${key}=${assemblyData[key]}`
      : null
  );
  const assemblyString = assemblyDataKeys
    .filter((item) => !!item)
    .join(splitIdentifier.joinSplit);
  return (
    url +
    (url.includes(splitIdentifier.identifier)
      ? splitIdentifier.joinSplit
      : splitIdentifier.identifier) +
    assemblyString
  );
}
